﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Entity.Validation;
using HYI.SDBSERVER;
using eHCBaseClass;
using Sunny.UI;

namespace SHRBASE
{
    public partial class FMI_PACK_MRK : SDBSERVER.FMSINGLE
    {
        //入口函数
        public static Int32 StartMe(string sMainPara, string sPara, string sUser, DBSERVER sDB)
        {
            StaticClass.Selectm_MainPara = sMainPara;
            StaticClass.SelectItemValue = sPara;
            StaticClass.SelectUser = sUser;
            StaticClass.myDB = sDB;
            return 0;
        }

        private string sType = "V";
        private string sSite_No = string.Empty;
        //DBSERVER myADO = new DBSERVER();
        DBCache myCache = new DBCache();
        private int iGridView = 0;
        private int iGridView2 = 0;
        private int detailindex = -1;
        DataTable myDetail;

        protected override void OnSys04()
        {
            string sDate1 = uiDate1.Text;
            string sDate2 = uiDate2.Text;
            string SQL = "select c.fdictname,a.*"
              + "  from i_pack_mrk_head a"
              + "  inner join s_ts_dict c on c.fdicttype = 2007 and c.fdictno = a.fbillstate"
              + "  where 1 = 1"
              + "  and a.fsite_No='" + sSite_No + "'"
              + "  and a.fmrkdate between '" + sDate1 + "'"
              + "  and '" + sDate2 + "'";
            DataRowView drv = (DataRowView)uiCBState.SelectedItem;
            if ((drv != null)&&(uiCBState.SelectedIndex>0))
            {
                string sfstorageflag = drv.Row["fDictNo"].ToString();
                SQL = SQL + " and c.fdictno='" + sfstorageflag + "'";
            }

            DataRowView drv2 = (DataRowView)cbfstockno.SelectedItem;
            if ((drv2 != null) && (cbfstockno.SelectedIndex > 0))
            {
                string sfstockno = drv2.Row["fstockno"].ToString();
                SQL = SQL + " and a.fstockno='" + sfstockno + "'";
            }

            DataRowView drv3 = (DataRowView)cbfmrkuser.SelectedItem;
            if ((drv3 != null) && (cbfmrkuser.SelectedIndex > 0))
            {
                string sfmrkuser = drv3.Row["id"].ToString();
                SQL = SQL + " and a.fmrkuser='" + sfmrkuser + "'";
            }

            if (qifbillno.Text != "")
            {
                SQL = SQL + " and a.fbillno like '%" + qifbillno.Text + "%'";
            }

            SQL = SQL + "  order by a.fmrkdate desc,a.fbillno desc";
            Qrytable = StaticClass.myDB.query(SQL);

            base.OnSys04();
            rowindex = -1;
            
        }

        public FMI_PACK_MRK()
        {
            InitializeComponent();
        }

        private void FMI_PACK_MRK_Load(object sender, EventArgs e)
        {
            _INPUTTABLE = "import_i_pack_mrk_detail";
            sUser = StaticClass.SelectUser;
            string[] strArray = StaticClass.Selectm_MainPara.Split(new char[] { ';' });
            sMenu = strArray[1];
            sSite_No = strArray[0];

            //按钮控制
            sys07.Visible = false; sys07.Tag = "1";
            sys08.Visible = false; sys08.Tag = "1";
            sys09.Visible = false; sys09.Tag = "1";
            sys11.Visible = true;  

            uiDate1.Text = DateTime.Now.ToString("yyyy-MM-dd");
            uiDate2.Text = DateTime.Now.ToString("yyyy-MM-dd");
            uifmrkdate.DateFormat = "yyyy-MM-dd";

            //下拉框
            DataTable myTs_Dict = myCache.doGetDict("S_TS_DICT", "fDictType=2007");
            uifbillstate.DataSource = myTs_Dict;
            uifbillstate.DisplayMember = "fDictName";
            uifbillstate.ValueMember = "fDictNo";

            DataRow dr1 = myTs_Dict.NewRow();
            dr1["fDictName"] = "请选择";
            dr1["fDictNo"] = "0";
            myTs_Dict.Rows.InsertAt(dr1, 0);
            uiCBState.DataSource = myTs_Dict;
            uiCBState.DisplayMember = "fDictName";
            uiCBState.ValueMember = "fDictNo";
            uiCBState.SelectedIndex = 0;

            DataTable myUser = myCache.doGetDict("AM_SYS_USER", "");
            uifmrkuser.DataSource = myUser;
            uifmrkuser.DisplayMember = "username";
            uifmrkuser.ValueMember = "id";

            DataRow dr2 = myUser.NewRow();
            dr2["username"] = "请选择";
            dr2["id"] = "0";
            myUser.Rows.InsertAt(dr2, 0);
            cbfmrkuser.DataSource = myUser;
            cbfmrkuser.DisplayMember = "username";
            cbfmrkuser.ValueMember = "id";
            cbfmrkuser.SelectedIndex = 0;

            DataTable myStock = myCache.doGetDict("I_TS_STOCK", "");
            uifstockno.DataSource = myStock;
            uifstockno.DisplayMember = "fstockname";
            uifstockno.ValueMember = "fstockno";

            DataRow dr3 = myStock.NewRow();
            dr3["fstockname"] = "请选择";
            dr3["fstockno"] = "0";
            myStock.Rows.InsertAt(dr3, 0);
            cbfstockno.DataSource = myStock;
            cbfstockno.DisplayMember = "fstockname";
            cbfstockno.ValueMember = "fstockno";
            cbfstockno.SelectedIndex = 0;

            //执行查询代码
            OnSys04();

            //表格列显示统一控制
            if (iGridView == 0)
            {
                myCache.doSetGridVIew(sMenu, sUser, uiDGView);
                iGridView = iGridView + 1;
            }
        }

        //执行审核代码
        protected override void OnSys11()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }

            int sfbillstate = int.Parse(uiDGView["fbillstate", rowindex].Value.ToString());

            if (sfbillstate > 1)
            {
                UIMessageTip.ShowOk("该单据不能审核");
                return;
            }

            string sBillNo = uiDGView["fBillNo", rowindex].Value.ToString();

            if (this.ShowAskDialog("确定审核单据(" + sBillNo + ")?"))
            {
                string SQL = "exec proc_biz_bizcenter 'i_pack_mrk_head','','" + sBillNo + "',2,'" + sUser + "'";
                DataTable myTable = StaticClass.myDB.query(SQL);
                this.ShowInfoDialog(myTable.Rows[0][0].ToString());

                OnSys04();
            }
        }

        //新增代码
        protected override void OnSys01()
        {
            uifbillno.Text = "";
            uifexplanation.Text = "";
            uifmrkdate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            uifbillstate.SelectedValue = "0";
            uifstockno.SelectedValue = "";
            uifmrkuser.SelectedValue = "";

            DataTable myNo = StaticClass.myDB.query("exec fun_billnumber 2031");
            if ((myNo != null) && (myNo.Rows.Count > 0))
            {
                uifbillno.Text = myNo.Rows[0][0].ToString();
            }
            sType = "A";
            doLoadData();
            uifbillno.ReadOnly = true;
            uifbillstate.ReadOnly = true;

            base.OnSys01();
        }

        //编辑+浏览载入数据
        private void doLoadData()
        {
            //控制界面输入
            Boolean input = false;
            if ((sType.Equals("A")) || (sType.Equals("B")))
            {
                input = false;
            }
            else
            {
                input = true;
            }
            foreach (Control ctrl in uiPanel1.Controls)
            {
                if (ctrl is UITextBox)
                {
                    UITextBox m = (UITextBox)ctrl;
                    m.ReadOnly = input;
                }

                if (ctrl is UIComboBox)
                {
                    UIComboBox m = (UIComboBox)ctrl;
                    m.ReadOnly = input;
                }
            }

            if (!sType.Equals("A"))
            {
                uifbillno.Text = uiDGView["fbillno", rowindex].Value.ToString();
                uifmrkdate.Text = uiDGView["fmrkdate", rowindex].Value.ToString();
                uifexplanation.Text = uiDGView["fexplanation", rowindex].Value.ToString();

                int i = 0;
                string sfbillstate = uiDGView["fbillstate", rowindex].Value.ToString();
                foreach (System.Data.DataRowView dr in uifbillstate.Items)
                {
                    string id = dr["fdictno"].ToString();
                    if (id.Equals(sfbillstate))
                    {
                        uifbillstate.SelectedIndex = i;
                        break;
                    }
                    i = i + 1;
                }

                i = 0;
                string sfmrkuser = uiDGView["fmrkuser", rowindex].Value.ToString();
                foreach (System.Data.DataRowView dr in uifmrkuser.Items)
                {
                    string id = dr["id"].ToString();
                    if (id.Equals(sfmrkuser))
                    {
                        uifmrkuser.SelectedIndex = i;
                        break;
                    }
                    i = i + 1;
                }

                i = 0;
                string sfstockno = uiDGView["fstockno", rowindex].Value.ToString();
                foreach (System.Data.DataRowView dr in uifstockno.Items)
                {
                    string id = dr["fstockno"].ToString();
                    if (id.Equals(sfstockno))
                    {
                        uifstockno.SelectedIndex = i;
                        break;
                    }
                    i = i + 1;
                }
            }

            //载入明细
            string sql = "select a.fbillno,a.fline,a.frfidbarcode,a.fpackno,b.fpackname,b.fspec"
              +"  from i_pack_mrk_detail a"
              +" inner join i_ts_pack b on a.fpackno = b.fpackno"
              + " where 1 = 1"
              + " and a.fbillno='" + uifbillno.Text + "'"
              + " order by fline";
            myDetail = StaticClass.myDB.query(sql);
            uiDetail.DataSource = myDetail;

            //表格列显示统一控制
            if (iGridView2 == 0)
            {
                myCache.doSetGridVIew(sMenu + "1", sUser, uiDetail);
                iGridView2 = iGridView2 + 1;
            }

            uibtn1.Visible = true;
            uibtn2.Visible = true;

            if (sType.Equals("V"))
            {
                uibtn1.Visible = false;
                uibtn2.Visible = false;
            }
            detailindex = -1;
        }

        //编辑代码
        protected override void OnSys02()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }

            int sfbillstate = int.Parse(uiDGView["fbillstate", rowindex].Value.ToString());

            if (sfbillstate > 1)
            {
                UIMessageTip.ShowOk("该单据不能修改");
                return;
            }

            sType = "B";

            doLoadData();

            uifbillno.ReadOnly = true;
            uifbillstate.ReadOnly = true;

            base.OnSys02();
        }

        //删除代码
        protected override void OnSys03()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }

            int sfbillstate = int.Parse(uiDGView["fbillstate", rowindex].Value.ToString());

            if (sfbillstate > 1)
            {
                UIMessageTip.ShowOk("该单据不能删除");
                return;
            }

            if (this.ShowAskDialog("确定删除(" + uiDGView["fbillno", rowindex].Value.ToString() + ")?"))
            {
                string sBillNo = uiDGView["fbillno", rowindex].Value.ToString();
                string SQL = "exec proc_biz_dodelete 'i_pack_mrk_head','','" + sBillNo + "',2,'" + sUser + "'";
                DataTable myTable = StaticClass.myDB.query(SQL);

                string sMsg = myTable.Rows[0][0].ToString();
                if (sMsg.Equals("OK"))
                {
                    this.ShowInfoDialog("删除完毕");
                    OnSys04();
                }
                else
                {
                    this.ShowInfoDialog(sMsg);
                }
            }
        }

        //浏览代码
        protected override void OnSys10()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }
            sType = "V";

            doLoadData();

            base.OnSys10();

        }

        //数据为空检查
        private bool CheckData()
        {
            return CheckEmpty(uifstockno, "请选择仓库")
                   && CheckEmpty(uifmrkuser, "请选择操作人员");
        }

        //保存代码
        protected override void OnSys08()
        {
            if (!CheckData())
            {
                return;
            }
            DataRowView drv1 = (DataRowView)uifbillstate.SelectedItem;
            string sfbillstate = drv1.Row["fDictNo"].ToString();

            DataRowView drv2 = (DataRowView)uifmrkuser.SelectedItem;
            string sfmrkuser = drv2.Row["id"].ToString();

            DataRowView drv3 = (DataRowView)uifstockno.SelectedItem;
            string sfstockno = drv3.Row["fStockNo"].ToString();

            //StaticClass.myDB.doWriteLog(1, this.Text+":"+sType);

            if (sType == "A")
            {
                try
                {
                    using (XTBasEntities context = new XTBasEntities())
                    {
                        i_pack_mrk_head myData = context.i_pack_mrk_head.Find(uifbillno.Text);
                        if (myData is null)
                        {
                            i_pack_mrk_head myData2 = new i_pack_mrk_head();
                            myData2.fbillno = uifbillno.Text;
                            myData2.fitemcount = myDetail.Rows.Count;
                            myData2.fpiececount = myDetail.Rows.Count;
                            myData2.ftotalamt = 0;
                            myData2.fexplanation = uifexplanation.Text;
                            myData2.fmrkdate = Convert.ToDateTime(uifmrkdate.Text);
                            myData2.foperator = sUser;
                            myData2.fupddate = DateTime.Now;
                            myData2.fsite_no = sSite_No;
                            myData2.fbillstate = int.Parse(sfbillstate);
                            myData2.fbilltype = 1;
                            myData2.fstockno = sfstockno;
                            myData2.fmrkuser = sfmrkuser;
                            context.i_pack_mrk_head.Add(myData2);
                            context.SaveChanges();
                            //StaticClass.myDB.doWriteLog(1, "添加成功");

                            doSetDetail();
                            UIMessageTip.ShowOk("添加成功");

                        }
                        else
                        {
                            //Console.WriteLine("添加成功");
                            //StaticClass.myDB.doWriteLog(1, "编号已存在:" + myData.fbillno.ToString());
                            UIMessageTip.ShowOk("编号已存在");
                            //Console.WriteLine("已存在");
                            return;
                        }

                    }
                }
                catch (DbEntityValidationException dbEx)
                {
                    Console.WriteLine("错误" + dbEx.Message);
                    StaticClass.myDB.doWriteLog(1,"错误:" + dbEx.Message);
                }
            }

            else if (sType == "B")
            {
                using (XTBasEntities context = new XTBasEntities())
                {
                    //查询
                    i_pack_mrk_head mypack_head = context.i_pack_mrk_head.Find(uifbillno.Text);

                    mypack_head.fitemcount = myDetail.Rows.Count;
                    mypack_head.fpiececount = myDetail.Rows.Count;
                    mypack_head.fexplanation = uifexplanation.Text;
                    mypack_head.fmrkdate = Convert.ToDateTime(uifmrkdate.Text);
                    mypack_head.foperator = sUser;
                    mypack_head.fupddate = DateTime.Now;
                    mypack_head.fbillstate = int.Parse(sfbillstate);
                    mypack_head.fstockno = sfstockno;
                    mypack_head.fmrkuser = sfmrkuser;
                    int result = context.SaveChanges();
                    doSetDetail();
                    UIMessageTip.ShowOk("修改成功");
                }
            }

            //刷新cache
            sType = "V";
            base.OnSys08();

            OnSys04();
        }

        private void uiDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            detailindex = e.RowIndex;
        }

        private void uiDetail_DoubleClick(object sender, EventArgs e)
        {
            string iMenu = sMenu + "1";
            OnGridDbClick(iMenu, uiDetail);
        }

        private void uibtn2_Click(object sender, EventArgs e)
        {
            //删除明细
            Console.WriteLine("行:" + detailindex.ToString());
            if (detailindex == -1)
            {
                UIMessageTip.ShowOk("请先选择要删除的记录");
                return;
            }
            if (this.ShowAskDialog("确定删除吗?"))
            {
                string iseq = myDetail.Rows[detailindex]["fline"].ToString();
                DataRow[] foundRow = myDetail.Select("fline = " + iseq, "");
                foreach (DataRow row in foundRow)
                {
                    myDetail.Rows.Remove(row);
                }
            }
        }

        private void uibtn1_Click(object sender, EventArgs e)
        {
            //添加明细 a.fseq,a.fequipmentbarcode,b.fmacno,b.fequipmenttag fcatname
            int i = 1;
            if (myDetail.Rows.Count > 0)
            {
                i = int.Parse(myDetail.Rows[myDetail.Rows.Count - 1]["fline"].ToString()) + 1;
            }

            //弹窗选择
            string sql= "select a.frfidbarcode,a.fpackno,b.fpackname,b.fspec"
               +" from i_pack_inv a,i_ts_pack b"
               +" where a.fstate = 1 and a.fpackno = b.fpackno";

            string DATA = doPOPWINDOS("容器标签查询"
                , "frfidbarcode,容器标签,121;fpackno,容器编号,121;fpackname,容器名称,161"
                , sql
                , " order by fpackno"
                ,1);
            Console.WriteLine("当前返回:" + DATA);

            if ((DATA is null) || (DATA.Length == 0))
            {
                return;
            }
            string[] strList = DATA.Split(';');

            for (int j = 0; j < strList.Length; j++)
            {
                string[] strArray = strList[j].Split(',');

                if (strArray.Length > 1)
                {
                    //存在不保存
                    DataRow[] foundRow = myDetail.Select("frfidbarcode = '" + strArray[0] + "'");
                    if (foundRow.Length == 0)
                    {
                        DataRow dr = myDetail.NewRow();
                        dr["fline"] = i.ToString(); ;
                        dr["frfidbarcode"] = strArray[0];
                        dr["fpackno"] = strArray[1];
                        dr["fpackname"] = strArray[2];
                        dr["fspec"] = strArray[3];
                        myDetail.Rows.InsertAt(dr, myDetail.Rows.Count);

                        i = i + 1;
                    }
                }
            }
        }

        //保存明细
        private Boolean doSetDetail()
        {
            bool IsOk = false;
            StaticClass.myDB.SQLList.Clear();
            string sql = "delete from i_pack_mrk_detail where fbillno='" + uifbillno.Text + "'";
            StaticClass.myDB.SQLList.Add(sql);

            for (int i = 0; i < myDetail.Rows.Count; i++)
            {
                sql = "insert into i_pack_mrk_detail(fbillno,fline,fpackno,frfidbarcode)"
                    + " values('" + uifbillno.Text + "'"
                    + "," + myDetail.Rows[i]["fline"].ToString()
                    + ",'" + myDetail.Rows[i]["fpackno"].ToString() + "'"
                    + ",'" + myDetail.Rows[i]["frfidbarcode"].ToString() + "'"
                    + ")";
                StaticClass.myDB.SQLList.Add(sql);
            }
            string sError = string.Empty;
            StaticClass.myDB.doSave(out IsOk, out sError);
            return IsOk;
        }

        private void uiCBState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (iGridView > 0)
            {
                OnSys04();
            }
        }

        private void cbfmrkuser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (iGridView > 0)
            {
                OnSys04();
            }
        }

        private void cbfstockno_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (iGridView > 0)
            {
                OnSys04();
            }
        }
    }
}
